package com.diko.commonUtils;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import com.alibaba.fastjson.TypeReference;
import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Emma Li
 * @date 2020/9/12 - 16:17
 */
@Data
public class R extends HashMap<String, Object> {
    @ApiModelProperty(value = "是否成功")
    private Boolean success;
    @ApiModelProperty(value = "返回码")
    private Integer code;
    @ApiModelProperty(value = "返回消息")
    private String message;
    @ApiModelProperty(value = "返回数据")
    private Map<String, Object> data = new HashMap<String, Object>();

    //将R私有化可以使别人不能调用R()但可以调用下面写的static方法
    private R(){}

//    public R() {
//        put("code", 0);
//        put("msg", "success");
//    }

    public  Integer getCode() {

        return (Integer) this.get("code");
    }

    public static R ok(){
        R r = new R();
        r.setSuccess(true);
        r.setCode(resultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R error(){
        R r = new R();
        r.setSuccess(false);
        r.setCode(resultCode.ERROR);
        r.setMessage("失败");
        return r;
    }
    //自己加的
    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }
    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }
    public R message(String message){
        this.setMessage(message);
        return this;
    }
    public R code(Integer code){
        this.setCode(code);
        return this;
    }
    public R data(String key, Object value){

        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map){

        this.setData(map);
        return this;
    }
    //自己加的
    public R data(Object data) {
        put("data", data);
        return this;
    }
    /**
     * 把map里key为data的数据转换成某个类型的数据
     * @param typeReference
     * @param <T>
     * @return
     */
    //自己加的
    public <T> T getData(TypeReference<T> typeReference) {
        Object obj = get("data");

        String json = JSON.toJSONString(obj);

        T t = JSON.parseObject(json, typeReference);

        return t;
    }

    public <T> T getData(String key, TypeReference<T> typeReference) {
        Object obj = get(key);

        String json = JSON.toJSONString(obj);

        T t = JSON.parseObject(json, typeReference);

        return t;
    }
}
